package com.download;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.administrator.futurehope.R;

public class ThreadDownloadActivity extends Activity {

	private Button cancel;
	private ProgressBar downloadProgressBar;
	private TextView downloadinfo;
	private int downloadedSize = 0;
	private int fileSize = 0;

	private long downloadtime;
	private String fileName, dowloadDir;
	private String URL;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.download_app);

		downloadinfo = (TextView) findViewById(R.id.downloadinfo);
		cancel = (Button) findViewById(R.id.cancel);
		downloadProgressBar = (ProgressBar) findViewById(R.id.downloadProgressBar);
		downloadProgressBar.setVisibility(View.VISIBLE);
		downloadProgressBar.setMax(100);
		downloadProgressBar.setProgress(0);
		Intent intent = getIntent();
		URL = intent.getStringExtra("URL");
		fileName = intent.getStringExtra("fileName");
		download();
		downloadtime = SystemClock.currentThreadTimeMillis();

		cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}

	private void download() {
		dowloadDir = Environment.getExternalStorageDirectory() + "/FHUC/";
		File file = new File(dowloadDir);
		if (!file.exists()) {
			file.mkdirs();
		}
		downloadProgressBar.setProgress(0);
		new downloadTask(URL, 1, dowloadDir + fileName).start();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// ���յ�������ͼ��Ϣʱ��������������ذٷֱȣ�ͬʱ���½������Ϣ
			int progress = (Double.valueOf((downloadedSize * 1.0 / fileSize * 100))).intValue();
			if (progress == 100) {
				cancel.setClickable(true);
				downloadinfo.setText("下载完毕");
				// Dialog mdialog = new AlertDialog.Builder(
				// ThreadDownloadActivity.this)
				// .setTitle("��ʾ��Ϣ")
				// .setMessage(
				// "������ɣ�����ʱΪ:"
				// + (SystemClock
				// .currentThreadTimeMillis() - downloadtime)
				// + "����")
				// .setNegativeButton("ȷ��",
				// new DialogInterface.OnClickListener()
				// {
				// @Override
				// public void onClick(DialogInterface dialog,
				// int which)
				// {
				// dialog.dismiss();
				// }
				// }).create();
				// mdialog.show();
				installApk();
				finish();
			} else {
				downloadinfo.setText("已下载:" + progress + "%");
			}
			downloadProgressBar.setProgress(progress);
		}

	};

	public class downloadTask extends Thread {
		private int blockSize, downloadSizeMore;
		private int threadNum = 5;
		String urlStr, threadNo, fileName;

		public downloadTask(String urlStr, int threadNum, String fileName) {
			this.urlStr = urlStr;
			this.threadNum = threadNum;
			this.fileName = fileName;
		}

		@Override
		public void run() {
			FileDownloadThread[] fds = new FileDownloadThread[threadNum];
			try {
				URL url = new URL(urlStr);
				URLConnection conn = url.openConnection();
//				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//				conn.setRequestMethod("GET");
//				if (conn.getResponseCode() == 200) {
					InputStream in = conn.getInputStream();
//				}
				// ��ֹ����-1
				// ��ȡ�����ļ����ܴ�С
				fileSize = conn.getContentLength();
				File file = new File(fileName);
				RandomAccessFile rfile = new RandomAccessFile(file, "rwd");
				rfile.setLength(fileSize);// �ѱ����ļ��ĳ�������Ϊ�����ļ��ĳ���
				rfile.close();

				Log.i("bb", "======================fileSize:" + fileSize);
				// ����ÿ���߳�Ҫ���ص������
				// blockSize = fileSize / threadNum;

				blockSize = fileSize % threadNum == 0 ? fileSize / threadNum : fileSize / threadNum + 1;// ����ÿ���߳����ص���ݳ���
				// �������ٷֱȼ������
				downloadSizeMore = (fileSize % threadNum);
				for (int i = 0; i < threadNum; i++) {
					Log.i("bb", "======================i:" + i);
					// �����̣߳��ֱ������Լ���Ҫ���صĲ���
					FileDownloadThread fdt = new FileDownloadThread(url, file, i * blockSize, (i + 1) * blockSize - 1);
					fdt.setName("Thread" + i);
					fdt.start();
					fds[i] = fdt;
				}
				boolean finished = false;
				while (!finished) {
					// �Ȱ���������㶨
					downloadedSize = downloadSizeMore;
					finished = true;
					for (int i = 0; i < fds.length; i++) {
						downloadedSize += fds[i].getDownloadSize();
						if (!fds[i].isFinished()) {
							finished = false;
						}
					}
					handler.sendEmptyMessage(0);
					// �߳���ͣһ��
					sleep(1000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	private void installApk() {
		File apkfile = new File(dowloadDir + fileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		this.startActivity(i);
	}

}